package com.farm.common.config;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class LocalDateConverter implements Converter<LocalDate> {


    /**
     * 转换成的Java类型
     */
    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }

    /**
     * Excel表中的类型
     */
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 在读取时，将Excel的值转换为Java值的规则
     */
    @Override
    public LocalDate convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String value = cellData.getStringValue();
        if (StringUtils.isNotBlank(value)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(value, formatter);
            return date;
        }
        if(CellDataTypeEnum.NUMBER == cellData.getType()){
            //时间为NUMBER时是以1900年为原点至所填时间，之间经过的天数
            Calendar calendar = new GregorianCalendar(1900,0,-1);
            Date date = DateUtils.addDays(calendar.getTime(), cellData.getNumberValue().intValue());
            return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        }
        return null;
    }

    /**
     * 在写入时，将Java的值转换为Excel值的规则
     */
    @Override
    public CellData convertToExcelData(LocalDate value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String valueString = value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if ("yyyy-MM-dd".equals(valueString)) {
            valueString = "";
        }
        return new CellData<>(valueString);
    }

}